package security;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 * Provides basic communication over TCP.
 * 
 * @author Lukas
 *
 */
public class TCPChannel implements Channel {
	private final Socket socket;
    private final PrintWriter out;
    private final BufferedReader in;
	
	/**
	 * Constructor; creates socket.
	 * @param host The host.
	 * @param port The TCP-Port.
	 * @throws IOException
	 * @throws UnknownHostException
	 */
	public TCPChannel(String host, int port) throws UnknownHostException, IOException {
		socket = new Socket(host, port);
        out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
	}
	
	/**
	 * Constructor; uses given socket.
	 * @param socket The socket.
	 * @throws IOException
	 */
	public TCPChannel(Socket socket) throws IOException {
		this.socket = socket;
        out = new PrintWriter(socket.getOutputStream(), true);
        in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
	}

	@Override
	public void send(String message) {
		out.println(message);
	}

	@Override
	public String receive() throws IOException {
		String message = in.readLine();
		if (message == null) {
			throw new IOException("Connection closed.");
		}
		return message;
	}

	@Override
	public void close() throws IOException {
		out.close();
		in.close();
		socket.close();
	}

}
